import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { ExtendedPageQuery } from './api';
import { auth } from "/@/utils/authFunction";
import { ElMessage } from 'element-plus';

interface RowData {
    id: string;
    description?: string;
    modifier?: string;
    dept_belong_id?: string;
    update_datetime?: string;
    create_datetime?: string;
    title: string;
    content: string;
    target_market: string;
    budget: number;
    execution_status: string;
    creator_id?: string;
}

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: UserPageQuery) => {
        try {
            const params: ExtendedPageQuery = {
                ...query,
                ordering: query.sort?.[0]?.asc ? query.sort[0].prop : `-${query.sort?.[0]?.prop}`
            };
            return await api.GetList(params);
        } catch (error) {
            ElMessage.error('获取数据失败');
            return Promise.reject(error);
        }
    };
    
    const editRequest = async ({ form, row }: EditReq) => {
        try {
            if (!row?.id) {
                throw new Error('记录ID不存在');
            }
            const editForm = { ...form, id: row.id };
            return await api.UpdateObj(editForm);
        } catch (error) {
            ElMessage.error('更新失败');
            return Promise.reject(error);
        }
    };
    
    const delRequest = async ({ row }: DelReq) => {
        try {
            if (!row?.id) {
                throw new Error('记录ID不存在');
            }
            return await api.DelObj(row.id);
        } catch (error) {
            ElMessage.error('删除失败');
            return Promise.reject(error);
        }
    };
    
    const addRequest = async ({ form }: AddReq) => {
        try {
            return await api.AddObj(form);
        } catch (error) {
            ElMessage.error('添加失败');
            return Promise.reject(error);
        }
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    add: {
                        text: "新增",
                        type: "primary",
                        icon: "plus",
                        show: auth('MarketingPlanModelViewSet:Create'),
                    }
                }
            },
            table: {
                border: true,
                stripe: true,
                highlight: true,
            },
            search: {
                show: true,
                buttons: {
                    search: {
                        text: "搜索",
                        icon: "search",
                        show: auth('MarketingPlanModelViewSet:Search')
                    },
                    reset: {
                        text: "重置",
                        icon: "refresh-right"
                    }
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 260,
                dropdown: {
                    more: {
                        text: '更多'
                    }
                },
                buttons: {
                    view: {
                        type: 'primary',
                        text: '查看',
                        icon: 'view',
                        order: 1,
                        show: auth('MarketingPlanModelViewSet:Retrieve')
                    },
                    edit: {
                        type: 'warning',
                        text: '编辑',
                        icon: 'edit',
                        order: 2,
                        show: auth('MarketingPlanModelViewSet:Update')
                    },
                    remove: {
                        type: 'danger',
                        text: '删除',
                        icon: 'delete',
                        order: 3,
                        show: auth('MarketingPlanModelViewSet:Delete')
                    },
                },
            },
            columns: {
                id: {
                    title: 'ID',
                    type: 'text',
                    column: {
                        width: 100,
                    },
                    form: {
                        show: false
                    }
                },
                title: {
                    title: '计划标题',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 160,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '计划标题必填' }],
                        component: {
                            placeholder: '请输入计划标题',
                            maxlength: 100,
                            showWordLimit: true,
                        },
                    },
                },
                content: {
                    title: '计划内容',
                    type: 'textarea',
                    column: {
                        minWidth: 200,
                    },
                    form: {
                        rules: [{ required: true, message: '计划内容必填' }],
                        component: {
                            placeholder: '请输入计划内容',
                            showWordLimit: true,
                            rows: 4,
                        },
                    },
                },
                target_market: {
                    title: '目标市场',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 150,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '目标市场必填' }],
                        component: {
                            placeholder: '请输入目标市场',
                            maxlength: 100,
                            showWordLimit: true,
                        },
                    },
                },
                budget: {
                    title: '预算',
                    type: 'number',
                    search: { show: false },
                    column: {
                        width: 120,
                        sortable: 'custom',
                        formatter: ({ value }) => {
                            return value ? `¥${value.toLocaleString()}` : '¥0';
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '预算必填' }],
                        component: {
                            placeholder: '请输入预算金额',
                            min: 0,
                            precision: 2,
                        },
                    },
                },
                execution_status: {
                    title: '执行状态',
                    type: 'dict-select',
                    dict: dict({
                        data: [
                            { value: 'planning', label: '计划中' },
                            { value: 'executing', label: '执行中' },
                            { value: 'completed', label: '已完成' },
                            { value: 'cancelled', label: '已取消' }
                        ]
                    }),
                    search: { show: true },
                    column: {
                        width: 100,
                        sortable: 'custom',
                        align: 'center',
                        formatter: ({ row }: { row: RowData }) => {
                            const statusMap: Record<string, { text: string; type: string }> = {
                                planning: { text: '计划中', type: 'info' },
                                executing: { text: '执行中', type: 'primary' },
                                completed: { text: '已完成', type: 'success' },
                                cancelled: { text: '已取消', type: 'danger' }
                            };
                            const status = statusMap[row.execution_status] || { text: row.execution_status, type: 'info' };
                            return <el-tag size="small" type={status.type}>{status.text}</el-tag>;
                        }
                    },
                    form: {
                        rules: [{ required: true, message: '执行状态必选' }],
                        component: {
                            placeholder: '请选择执行状态',
                        },
                    },
                },
                description: {
                    title: '备注',
                    type: 'textarea',
                    column: {
                        minWidth: 150,
                    },
                    form: {
                        component: {
                            placeholder: '请输入备注信息',
                            maxlength: 255,
                            showWordLimit: true,
                        }
                    }
                },
                create_datetime: {
                    title: '创建时间',
                    type: 'datetime',
                    column: {
                        width: 180,
                        sortable: 'custom',
                    },
                    form: {
                        show: false
                    }
                },
                update_datetime: {
                    title: '更新时间',
                    type: 'datetime',
                    column: {
                        width: 180,
                        sortable: 'custom',
                    },
                    form: {
                        show: false
                    }
                }
            }
        }
    };
} 